package com.htjx.mall.services;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import com.htjx.mall.commons.mappers.AddresseeMapper;
import com.htjx.mall.commons.mappers.UserMapper;
import com.htjx.mall.commons.models.Addressee;
import com.htjx.mall.commons.models.User;
import com.htjx.mall.commons.models.enums.SeqType;

@Service
public class AddresseeService {
	@Autowired
	private AddresseeMapper addresseeMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private SequenceManager sequenceManager;
	@Autowired
	private TransactionTemplate transactionTemplate;
	
	public void insertOne(final Addressee addressee, final User user, final boolean prime) {
		long[] seq = sequenceManager.buildBatchSeq(SeqType.Addressee, 1);
		addressee.setId(seq[0]);
		if(prime) {
			user.setAddressee_id(addressee.getId());
		}
		transactionTemplate.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				addresseeMapper.insertOne(addressee);
				if(prime) {
					userMapper.updateOne(user);
				}
			}
		});
	}
	/****
	 * 更新收件人信息
	 */
	
	public void updateOne(final Addressee addressee, final User user, final boolean prime) {
		if(prime) {
			user.setAddressee_id(addressee.getId());
		}
		transactionTemplate.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				addresseeMapper.updateOne(addressee);
				if(prime) {
					userMapper.updateOne(user);
				}
			}
		});
	}
	
	public void deleteOne(final long id, final User user) {
		transactionTemplate.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				addresseeMapper.deleteOne(id);
				if(id == user.getAddressee_id()) {
					List<Addressee> addresseeList = null;
					addresseeList = selectByUserId(user.getId());
					if(addresseeList.size() > 0) {
						user.setAddressee_id(addresseeList.get(0).getId());
					} else {
						user.setAddressee_id(0);
					}
					userMapper.updateOne(user);
				}
			}
		});
	}
	
	
	public Addressee selectById (long id) {
		return addresseeMapper.selectById(id);
	}
	
	public List<Addressee> selectByUserId (long userId) {
		return addresseeMapper.selectByUserId(userId);
	}
}
